<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="小程序appid" prop="appid">
        <el-input
          v-model="queryParams.appid"
          placeholder="请输入小程序appid"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="小程序名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入小程序名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属机构" prop="deptId">
        <treeselect  v-model="queryParams.deptId"  class="treeselect-main" :options="deptOptions" :show-count="true" placeholder="请选择归属机构" />
      </el-form-item>
      <el-form-item label="联系电话" prop="principalPhone">
        <el-input
          v-model="queryParams.principalPhone"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wechat:applet:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appletList" >
      <el-table-column label="appid" align="center" prop="appid" />
      <el-table-column label="小程序名称" align="center" prop="nickName" />
      <el-table-column label="所属机构" align="center" prop="deptName" />
      <el-table-column label="商户ID" align="center" prop="mchId" />
      <el-table-column label="商户密钥" align="center" prop="mchKey" />
      <el-table-column label="创建人" align="center" prop="createUserName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="小程序主体名称" align="center" prop="principalName" />
      <el-table-column label="联系电话" align="center" prop="principalPhone" width="110" />
      <el-table-column label="小程序主要业务介绍" align="center" prop="signature" />
      <el-table-column label="支付状态" align="center" prop="openPay">
        <template slot-scope="scope">
          <span v-if="scope.row.openPay == 1" style="color: green">已开通</span>
          <span v-else style="color: red">未开通</span>
        </template>
      </el-table-column>
      <el-table-column label="开通状态" align="center" prop="openStatus">
        <template slot-scope="scope">
          <dict-tag :options="openStatusOptions" :value="scope.row.openStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="服务开通时间" align="center" prop="openTime" />
      <el-table-column label="服务截止时间" align="center" prop="closeTime" />
      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column label="授权状态" align="center" prop="authStatus" >
        <template slot-scope="scope">
          <span v-if="scope.row.authStatus == 0" style="color: green">已授权</span>
          <span v-else style="color: red">未授权</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="155">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleCreateQRCode(scope.row)"
            v-hasPermi="['wechat:applet:edit']"
          >授权码</el-button>
          <el-button
            v-if="scope.row.openStatus =='1'"
            size="mini"
            type="text"
            @click="applyOpen(scope.row)"
            v-hasPermi="['wechat:applet:edit']"
          >申请开通</el-button>
          <el-button
            v-if="scope.row.openStatus =='0'"
            size="mini"
            type="text"
            @click="applyClose(scope.row)"
            v-hasPermi="['wechat:applet:edit']"
          >申请关停</el-button>
          <el-button
            v-if="scope.row.openStatus =='2' || scope.row.openStatus =='3'"
            size="mini"
            type="text"
            @click="handleExamine(scope.row)"
            v-hasPermi="['wechat:applet:examine']"
          >审核</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['wechat:applet:edit', 'wechat:applet:remove']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleRefresh" icon="el-icon-key">刷新授权账号信息</el-dropdown-item>
              <el-dropdown-item command="handleUpdate" icon="el-icon-key"
                                v-hasPermi="['wechat:applet:edit']">修改</el-dropdown-item>
              <el-dropdown-item command="handleDelete" icon="el-icon-circle-check"
                                v-hasPermi="['wechat:applet:remove']">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小程序商户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属机构" prop="deptId">
          <treeselect  v-model="form.deptId"  :options="deptOptions" :show-count="true" placeholder="请选择归属机构" />
        </el-form-item>
        <el-form-item label="appid" prop="appid">
          <el-input v-model="form.appid" placeholder="请输入小程序appid" />
        </el-form-item>
        <el-form-item label="商户ID" prop="mchId">
          <el-input v-model="form.mchId" placeholder="商户ID" />
        </el-form-item>
        <el-form-item label="商户密钥" prop="mchKey">
          <el-input v-model="form.mchKey" placeholder="商户密钥" />
        </el-form-item>
        <el-form-item label="联系电话" prop="principalPhone">
          <el-input v-model="form.principalPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 授权二维码 -->
    <el-dialog :title="title" @opened="createQRCode" :visible.sync="qrcodeOpen" width="500px" append-to-body>
     <div  style="text-align: center">
       <div>
         <el-button style="margin-bottom: 30px" type="primary" plain @click="createQRCode">刷新</el-button>
       </div>
       <div style="margin: 20px auto;">
         <div  id="qrCode" ref="qrCodeDiv" style="height: 250px;width: 250px;margin: 0 auto"></div>
       </div>
       <div slot="footer" class="dialog-footer">
         <el-button @click="cancel">关 闭</el-button>
       </div>
     </div>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog :title="title" :visible.sync="examineOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="小程序名称" prop="appid">
          {{form.nickName}}
        </el-form-item>
        <el-form-item label="appid" prop="appid">
          {{form.appid}}
        </el-form-item>
        <el-form-item label="申请诉求" prop="principalPhone">
          {{form.openStatus == "2"? "申请开通":"申请关停"}}
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitExamine(0)">同 意</el-button>
        <el-button type="danger" @click="submitExamine(1)">拒 绝</el-button>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listApplet, getApplet, delApplet, addApplet, updateApplet, changeAppletStatus} from "@/api/wechat/applet";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeselect} from "@/api/system/dept";
import {getAuthorizationLink} from "@/api/wechat/wechat";
import QRCode from "qrcodejs2";
import {refreshApplet} from "../../../api/wechat/applet";
export default {
  name: "Applet",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序商户表格数据
      appletList: [],
      // 机构树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      appid: "",
      // 是否显示弹出层
      open: false,
      qrcodeOpen: false,
      examineOpen: false,
      // 支付状态开通标志：0为开通，1为未开通字典
      openPayOptions: [],
      // 系统管理员对小程序是否开通的操作状态：0为开通；1为未开通字典
      openStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appid: null,
        nickName: null,
        deptId: null,
        principalPhone: null
      },
      // 表单参数
      form: {},
      // 表单校验
      // 表单校验
      rules: {
        appid: [
          { required: true, message: "小程序appid不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "小程序所属机构ID，创建用户的所属机构ID不能为空", trigger: "blur" }
        ],
        principalPhone:[
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("wechat_status").then(response => {
      this.openStatusOptions = response.data;
      console.log(this.openStatusOptions)
    });
  },
  methods: {
    /** 查询小程序商户列表 */
    getList() {
      this.loading = true;
      listApplet(this.queryParams).then(response => {
        this.appletList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询机构下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.qrcodeOpen = false;
      this.examineOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        appid: null,
        nickName: null,
        deptId: null,
        mchId: null,
        mchKey: null,
        createUser: null,
        createTime: null,
        principalName: null,
        principalPhone: null,
        signature: null,
        openPay: "0",
        openStatus: "1",
        openTime: null,
        closeTime: null,
        remarks: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小程序商户";
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleRefresh":
          this.handleRefresh(row);
          break;
        default:
          break;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getApplet(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小程序商户";
      });
    },
    handleRefresh(row){
      refreshApplet(row.appid).then(response =>{
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApplet(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApplet(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id
      this.$confirm('是否确认删除小程序商户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApplet(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    handleCreateQRCode(row){
      this.appid = row.appid;
      this.qrcodeOpen = true;
      this.title = "小程序授权";
    },
    createQRCode(){
      document.getElementById("qrCode").innerHTML = "";
      getAuthorizationLink(this.appid).then(res =>{
         new QRCode(this.$refs.qrCodeDiv, {
           text: res,
           width: 250,
           height: 250,
           colorDark: "#1890FF", //二维码颜色
           colorLight: "#ffffff", //二维码背景色
           correctLevel: QRCode.CorrectLevel.H//容错率，L/M/H
         })
        console.log(res)
      })
    },
    applyOpen(row){
      this.$confirm('确认要申请开通小程序'+row.nickName+'吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        row.openStatus = "2";
        return changeAppletStatus(row.id, "2");
      }).then(() => {
        this.msgSuccess( "申请开通已提交");
      }).catch(function() {
        row.openStatus = "1";
      });
    },
    applyClose(row){
      this.$confirm('确认要申请关停小程序'+row.nickName+'吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        row.openStatus = "3";
        return changeAppletStatus(row.id, "3");
      }).then(() => {
        this.msgSuccess( "申请关停已提交");
      }).catch(function() {
        row.openStatus = "0";
      });
    },
    //审核
    handleExamine(row){
      getApplet(row.id).then(response => {
        this.form = response.data;
        this.title ="小程序审核"
        this.examineOpen = true;
      });
    },
    submitExamine(type){
      let openStatus;
      if(type == 0){
        if(this.form.openStatus == "2"){
          openStatus = "0"
        }else if(this.form.openStatus == "3"){
          openStatus = "1"
        }
      }else {
        if(this.form.openStatus == "2"){
          openStatus = "1"
        }else if(this.form.openStatus == "3"){
          openStatus = "0"
        }
      }
      changeAppletStatus(this.form.id, openStatus).then(res=>{
        this.examineOpen =false;
        this.getList();
        this.msgSuccess("审核完成")
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  .treeselect-main {
    width: 204px;
    line-height: 32px;
    .vue-treeselect__placeholder {
      line-height: 32px;
    }
    .vue-treeselect__control {
      height: 32px !important;
    }
  }
</style>
